package com.github.jcooky.structure;

public class ArrayQueue implements Queue {
	private Object[] Q;
	private int f = 0, r = 0;
	
	public ArrayQueue(int capacity) {
		Q = new Object[capacity];
	}

	public int size() {
		return (Q.length - (f - r)) % Q.length;
	}

	public boolean isEmpty() {
		return f == r;
	}

	public Object front() throws EmptyQueueException {
		if (f < 0)
			throw new EmptyQueueException();
		
		return Q[f];
	}

	public void enqueue(Object o) throws FullQueueException {
		if (size() == Q.length - 1)
			throw new FullQueueException();
		else {
			Q[r] = 0;
			r = (r + 1) % Q.length;
		}
	}

	public Object dequeue() throws EmptyQueueException {
		if (isEmpty())
			throw new EmptyQueueException();
		else {
			Object o = Q[f];
			f = (f + 1) % Q.length;
			return o;
		}
	}

	public Iterator iterator() {
		return new Iterator() {
			private int index = f;
			
			public boolean hasNext() {
				return index < r;
			}

			public Object next() {
				return Q[f++];
			}
			
		};
	}
}
